#!/usr/bin/env python
#-*- coding:utf-8 -*-
# 

#Copyright (c) 2009 

#file: makeversion.py
#date: 2015-10-12 09:26:01
#author: chuanjiang.zh@qq.com
#desc: 
#

import os

def rfind_digit(s, fromIdx, toIdx):
    for i in range(fromIdx, toIdx):
        idx = toIdx - 1 - i
        if s[idx].isdigit():
            return idx
    return -1

def rfind_not_digit(s, fromIdx, toIdx):
    for i in range(fromIdx, toIdx):
        idx = toIdx - 1 - i
        if not s[idx].isdigit():
            return idx
    return -1
    
    
def find_last_int(line):
    '''从尾部开始查找整数, 返回下标范围'''
    endIdx = rfind_digit(line, 0, len(line))
    beginIdx = rfind_not_digit(line, 0, endIdx)
    value = line[beginIdx+1:endIdx+1]
    return (beginIdx+1, endIdx+1)

def increase_num(line, linename):
    idx = line.find(linename)
    if idx == -1:
        return None
    (fromIdx, toIdx) = find_last_int(line)
    version = int(line[fromIdx:toIdx])
    version += 1
    newline = line[0:fromIdx] + str(version) + line[toIdx:]
    return (newline, version)

def increase_version(filename, linename):
    version = ""
    print(filename)
    lines = []
    with open(filename, "r") as f:
        for line in f:
            if not line.find(linename) != -1:
                lines.append(line)
                continue
            (newline, version) = increase_num(line, linename)
            lines.append(newline)
            print(version)
    with open(filename, 'w') as f:
        for line in lines:
            f.write(line)
    return version

def test():
    pass
    
def main():
    increase_version("../trans/CMakeLists.txt", "CPACK_PACKAGE_VERSION_PATCH")
    increase_version("../trans/Version.h", "APP_VERSION")
    
if __name__ == "__main__":
    main()
    
